﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="History.aspx.cs" Inherits="CRMWeb.Pages.History" ValidateRequest="false" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <link rel="stylesheet" id="newtheme" type="text/css" href="/EasyUI/Themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="/Css/CrmStyle.css" />
    <script type="text/javascript" src="/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/EasyUI/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/tiny_mce/tiny_mce.js"></script>
    <style type="text/css">
        #pnlMain {
            padding: 20px 0 0 0;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <label id="lblType" style="display: none"></label>
        <div id="pnlMain" title=" History Information " class="easyui-panel" style="width: auto; height: auto">
            <div class="fitem">
                <label style="width: 100px; margin-left: 10px">History Date:</label>
                <input id="txthistorydate" name="HistoryDate" class="easyui-datebox" data-options="formatter:formatDate" style="width: 100px;" />
            </div>
            <div class="fitem">
                <label style="width: 100px; margin-left: 10px">History Time:</label>
                <input id="txthistorytime" name="HistoryTime" class="easyui-timespinner" data-options="min:'00:01',max:'12:00'" style="width: 80px;" />
                <select id="cmbampm" class="easyui-combobox" data-options="panelHeight:'auto'" name="ampm" style="width: 60px;" required="true">
                    <option value="AM">AM</option>
                    <option value="PM">PM</option>
                </select>
                <label id="lblampm"></label>
            </div>
            <div class="fitem">
                <label style="width: 100px; margin-left: 10px">Action:</label>
                <input id="cmbaction" class="easyui-combotree" data-options="panelHeight:'auto',onSelect:setDescription" editable="true" animate="true" name="Action" style="width: 200px;" required="true" />


            </div>
            <div class="fitem">
                <label style="width: 100px; margin-left: 10px">Operator:</label>
                <input id="txtoperator" class="easyui-validatebox" />
            </div>
            <div class="fitem">
                <label style="width: 100px; margin-left: 10px">Description:</label>
                <div data-options="region:'center'" style="padding: 10px; height: 68%" class="emailbox">
                    <textarea id="txthdescription" name="txthdescription" style="width: 100%; height: 370px"></textarea>
                </div>
            </div>
            <input type="hidden" runat="server" id="hdnUserName" />
            <asp:ScriptManager ID="sm1" runat="server" EnablePageMethods="true" ScriptMode="Release"></asp:ScriptManager>
            <div class="fitem">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript:window.close()" style="float: left; margin-left: 10px">Cancel</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" onclick="saveHistory()" style="float: right; margin-right: 10px">Save</a>
            </div>
        </div>
    </form>
</body>

<script type="text/javascript">

    var selectUrl = '';

    tinyMCE.init({
        mode: "exact",
        elements: "txthdescription",
        theme: "advanced",
        plugins: "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
        theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,help,code,|,forecolor,backcolor",
        theme_advanced_font_sizes: "10px,12px,13px,14px,16px,18px,20px,24px",
        setup: function (ed) {
            ed.onInit.add(function (ed) {
                ed.getDoc().body.style.fontSize = '14px';
            });
            ed.onKeyDown.add(function (ed, e) {
                if ((e.which == 83 || e.which == 115) && (e.ctrlKey || e.metaKey) || (e.which == 19)) {
                    e.preventDefault();
                    saveHistory();
                    return false;
                }
            });
        }
    });


    function getQuerystring(key, defaultValue) {
        if (defaultValue == null) defaultValue = "";
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href);

        if (qs == null || qs == 'null' || qs == '')
            return defaultValue;
        else {
            if (qs[1] == 'null' || qs[1] == null || qs[1] == '')
                return defaultValue;
            else
                return qs[1];
        }
    }

    function formatDate(value, row) {
        if (value == null)
            return value;
        var date = new Date(value);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
    }

    $(document).keydown(function (event) {
        if ((event.which == 83 || event.which == 115) && (event.ctrlKey || event.metaKey) || (event.which == 19)) {
            event.preventDefault();
            saveHistory();
            return false;
        }
        return true;
    });

    function saveHistory() {
        var historytype = $('#lblType').text();
        var history_id = getQuerystring('historyid', 0);
        var contact_id = getQuerystring('contactid', 0);
        var app_id = getQuerystring('app_id', 0);
        //var t = $('#cmbaction').combotree('tree');
        //var n = t.tree('getSelected');

        var action = action = $('#cmbaction').combotree('getText');;

        var hdate = DefaultformatHistoryDate($('#txthistorydate').datebox('getValue'));
        var hdesc = encodeURIComponent(tinyMCE.get('txthdescription').getContent());
        var htime = $('#txthistorytime').val() + $('#cmbampm').combobox('getValue');
        htime = setHistoryTimeTo24(htime) + ':00';
        if (history_id > 0) {
            // Edit History
            PageMethods.UpdateHistory(historytype, history_id, contact_id, hdate, htime, action, $('#txtoperator').val(), hdesc, app_id);
            setTimeout(function () {
                window.close();
            }, 100);
        }
        else if (history_id == 0) {
            // Add New History
            PageMethods.saveNewHistory(historytype, contact_id, hdate, htime, action, $('#txtoperator').val(), hdesc, app_id);

            setTimeout(function () {
                window.close();
            }, 100);
        }
    }

    function DefaultformatHistoryDate(value) {
        var dArr = value.split('/');
        return dArr[1] + '/' + dArr[0] + '/' + dArr[2];
    }

    function setHistoryTimeTo12(value) {
        var hourEnd = value.indexOf(':');
        var H = +value.substr(0, hourEnd);
        var ampm = '';
        var minutes = value.substring(3, 5);
        if (H == 12 && minutes > 00) {
            value = '00:' + minutes;
            ampm = 'PM';
        }
        else if (H == 00 && minutes > 00) {
            value = '00:' + minutes;
            ampm = 'AM';
        }
        else {
            var h = H % 12 || 12;
            ampm = H < 12 ? 'AM' : 'PM';
            value = h + value.substr(hourEnd, 3);
        }
        $('#cmbampm').combobox('setValue', ampm);
        $('#txthistorytime').timespinner('setValue', value);
    }
    function setHistoryTimeTo24(timeStr) {
        var meridian = timeStr.substr(timeStr.length - 2).toLowerCase();;
        var hours = timeStr.substr(0, timeStr.indexOf(':'));
        var minutes = timeStr.substring(3, 5);
        if (meridian == 'pm') {
            if (hours != 12)
                hours = hours * 1 + 12;
        }
        else {
            if (hours == 12)
                hours = 00;
        }
        return hours + ':' + minutes;
    }
    window.onresize = function () {
        $('#pnlMain').panel('resize', {
            width: window.innerWidth - 5,
            height: window.innerHeight - 5
        });
    }


    $('#cmbaction').combotree({
        formatter: function (node) {
            var val = node.text;
            var data = [];
            if (val.indexOf('_') > 0)
                data = val.split('_');

            if (data.length > 1)
                return data[1];
            else
                return val;
        }
    });


    function setDescription() {
        var t = $('#cmbaction').combotree('tree');
        var n = t.tree('getSelected');
        if (n.id > 0) {
            $.messager.alert('Morgan CRM', 'Select valid Action');
            return;
        }
        if (n.id == 'Verification_Car Rego') {
            var strdata = decodeURIComponent("%3Cp%3EName%3A%3C%2Fp%3E%0A%3Cp%3EExpiry%3A%3C%2Fp%3E%0A%3Cp%3EPlate%3A%3C%2Fp%3E%0A%3Cp%3EMake%3A%3C%2Fp%3E%0A%3Cp%3EModel%3A%3C%2Fp%3E%0A%3Cp%3EVIN%3A%3C%2Fp%3E");
            tinymce.get('txthdescription').setContent(strdata);
        }
    }

    $(document).ready(function () {

        $('#newtheme').attr('href', '/EasyUI/Themes/' + getQuerystring('Theme', 'Default') + '/easyui.css');

        $('#lblType').html(getQuerystring('type', ''));

        $('#cmbaction').combotree('loadData', [{
            id: '1',
            text: 'Call',
            children: [{
                id: 'Call_Incomming',
                text: 'Call_Incomming'
            }, {
                id: 'Call_Outgoing',
                text: 'Call_Outgoing'
            }]
        }, {
            id: '2',
            text: 'Email',
            children: [{
                id: 'Email_Received',
                text: 'Email_Received'
            }, {
                id: 'Email_Docs Received',
                text: 'Email_Docs Received'
            }, {
                id: 'Email_Sent',
                text: 'Email_Sent'
            }]
        }, {
            id: '3',
            text: 'Fax',
            children: [{
                id: 'Fax_Received',
                text: 'Fax_Received'
            }, {
                id: 'Fax_Sent',
                text: 'Fax_Sent'
            }]
        }, {
            id: '4',
            text: 'SMS',
            children: [{
                id: 'SMS_Received',
                text: 'SMS_Received'
            }, {
                id: 'SMS_Sent',
                text: 'SMS_Sent'
            }]
        }, {
            id: '5',
            text: 'Post',
            children: [{
                id: 'Post_Received',
                text: 'Post_Received'
            }, {
                id: 'Post_Sent',
                text: 'Post_Sent'
            }]
        }, {
            id: '6',
            text: 'Verification',
            children: [{
                id: 'Verification_Car Rego',
                text: 'Verification_Car Rego'
            }, {
                id: 'Verification_Witness',
                text: 'Verification_Witness'
            }, {
                id: 'Verification_Bank Account',
                text: 'Verification_Bank Account'
            }, {
                id: 'Verification_Applicant ID',
                text: 'Verification_Applicant ID'
            }, {
                id: 'Verification_Others',
                text: 'Verification_Others'
            }]
        }, {
            id: 'Live Chat',
            text: 'Live Chat'
        }, {
            id: 'Came to office',
            text: 'Came to office'
        }, {
            id: 'Field Changed(system)',
            text: 'Field Changed(system)'
        }
        ]);

        $('#cmbampm').combobox('textbox').bind('click', function () {
            $('#cmbampm').combobox('showPanel');
        });
        $('#cmbaction').combobox('textbox').bind('click', function () {
            $('#cmbaction').combobox('showPanel');
        });
        $('#pnlMain').panel('resize', {
            width: window.innerWidth - 5,
            height: window.innerHeight - 5
        });
        if (getQuerystring('Operation', '') == 'new') {
            if ($('#lblType').text() == 'Application') {
                $('#pnlMain').panel('setTitle', 'New Application History Information');
            }
            else if ($('#lblType').text() == 'Contact') {
                $('#pnlMain').panel('setTitle', 'New Contact History Information');
            }
            $('#txthistorydate').datebox('setValue', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());
            $('#txthistorytime').timespinner('setValue', '');
            var currTime = new Date().getHours() + ':' + new Date().getMinutes();
            setHistoryTimeTo12(currTime);
            $('#cmbaction').combotree('setValue', '');
            $('#txtoperator').val($('#hdnUserName').val());
            $('#txtoperator').attr("readonly", true);

        }
        else if (getQuerystring('Operation', '') == 'edit') {
            if ($('#lblType').text() == 'Application') {
                $('#pnlMain').panel('setTitle', 'Edit Application History Information');
                selectUrl = '/WebServices/History.ashx?method=SelectHistoryByID&historyType=Application';
            }
            else if ($('#lblType').text() == 'Contact') {
                $('#pnlMain').panel('setTitle', 'Edit Contact History Information');
                selectUrl = '/WebServices/History.ashx?method=SelectHistoryByID&historyType=Contact';
            }
            $.ajax({
                url: selectUrl,
                data: { historyID: getQuerystring('historyid', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {

                        $('#cmbaction').combotree('setText', rec.Action);


                        $('#txthistorydate').datebox('setValue', formatDate(rec.HistoryDate, null));
                        setHistoryTimeTo12(rec.HistoryTime);

                        $('#txtoperator').val($('#hdnUserName').val());
                        $('#txtoperator').attr("readonly", true);
                        var temp = decodeURIComponent(rec.Description);
                        setTimeout(function () {
                            tinymce.activeEditor.formatter.apply('fontsize', { value: '13' });
                            tinymce.get('txthdescription').setContent(temp);
                        }, 50);
                        $('#cmbaction').combotree('setValue', rec.Action);
                    });
                }
            });
        }
    });

</script>
</html>
